package com.peng.sell.controller;

import com.peng.sell.config.ProjectUrlConfig;
import com.peng.sell.constant.CookieConst;
import com.peng.sell.constant.RedisConst;
import com.peng.sell.dataobject.SellerInfo;
import com.peng.sell.enums.ResponseCodeEnum;
import com.peng.sell.exception.SellException;
import com.peng.sell.service.SellerService;
import com.peng.sell.utils.CookieUtil;
import com.peng.sell.utils.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/seller")
public class SellerUserController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    ProjectUrlConfig projectUrlConfig;


    @GetMapping("/login")
    public String  login(String openid, Map<String,Object> map, HttpServletResponse response){

        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
        if(sellerInfo==null){
            map.put("msg",ResponseCodeEnum.LOGIN_FAIL.getDesc());
            map.put("url","/sell/seller/order/list");
            return "/common/error";
        }
        String token = KeyUtil.getUUID();

        //存入redis
        redisTemplate.opsForValue().set(String.format(RedisConst.TOKEN_PREFIX,token),openid,RedisConst.EXPIRE,TimeUnit.SECONDS);
        //写入cookie
        CookieUtil.set(response,CookieConst.TOKEN,token,CookieConst.EXPIRE);
        return "redirect:"+projectUrlConfig.getSell()+"/sell/seller/order/list";






    }
    @GetMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response,Map<String,Object> map){

        //取出cookie
        Cookie cookie = CookieUtil.get(request, CookieConst.TOKEN);
        if(cookie!=null){
            //清除redis
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConst.TOKEN_PREFIX,cookie.getValue()));
            //清除cookie
            CookieUtil.set(response,CookieConst.TOKEN,null,0);
        }
        map.put("msg",ResponseCodeEnum.LOGOUT_SUCCESS.getDesc());
        map.put("url","/sell/seller/order/list");
        return "common/success";


    }
}
